package com.feeyo.prophet.service;

import com.feeyo.prophet.mongo.dao.ChatRecordRepository;
import com.feeyo.prophet.pojo.dto.ChatRecordDTO;
import com.feeyo.prophet.pojo.enums.ContentTypeEnum;
import com.feeyo.prophet.pojo.enums.UsefulnesEnum;
import com.feeyo.prophet.pojo.po.ChatRecord;
import com.mongodb.client.result.UpdateResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ChatRecordService {

    private final ChatRecordRepository chatRecordRepository;

    private final MongoTemplate mongoTemplate;


    @Autowired
    public ChatRecordService(ChatRecordRepository chatRecordRepository, MongoTemplate mongoTemplate) {
        this.chatRecordRepository = chatRecordRepository;
        this.mongoTemplate = mongoTemplate;
    }

    public ChatRecord insert(String lastId, String appId, String conversationId, String content, ContentTypeEnum contentType, String actions, Integer type) {
        ChatRecord chatRecord = assignment(lastId, appId, conversationId, content, contentType, actions, type);
        return chatRecordRepository.insert(chatRecord);
    }

    public ChatRecord assignment(String lastId, String appId, String conversationId, String content, ContentTypeEnum contentType, String actions, Integer type) {
        ChatRecord chatRecord = new ChatRecord();
        chatRecord.setLastId(lastId);
        chatRecord.setAppId(appId);
        chatRecord.setConversationId(conversationId);
        chatRecord.setContent(content);
        chatRecord.setContentType(contentType.name());
        // 后续可能是多个
        chatRecord.setActions(actions);
        chatRecord.setType(type);
        chatRecord.setUsefulness(UsefulnesEnum.NON.getCode());
        chatRecord.setFeedback(StringUtils.EMPTY);
        chatRecord.setDeleted(false);
        chatRecord.setValuableScore(60);
        LocalDateTime now = LocalDateTime.now();
        chatRecord.setUpdateTime(now);
        chatRecord.setCreateTime(now);
        return chatRecord;
    }


    /**
     * 分页查询
     */
    public Page<ChatRecord> page(String appId, String conversationId, Integer pageNum, Integer pageSize) {
        // 创建分页和排序条件
        Pageable pageable = PageRequest.of(pageNum, pageSize, Sort.by(Sort.Direction.DESC, "_id"));
        Criteria criteria = Criteria.where("appId").is(appId)
                .and("valuableScore").gte(60)
                .and("deleted").is(false);
        // 如果 conversationId 不为空，则添加该条件
        if (conversationId != null && !conversationId.isEmpty()) {
            criteria.and("conversationId").is(conversationId);
        }

        Query query = new Query(criteria).with(pageable);
        long total = mongoTemplate.count(query, ChatRecord.class);
        List<ChatRecord> records = mongoTemplate.find(query, ChatRecord.class);
        return new PageImpl<>(records, pageable, total);
    }

    public boolean updateUserFeedback(String id, Integer usefulness, String feedback) {
        Query query = new Query(Criteria.where("id").is(id));
        if (StringUtils.isBlank(feedback)) {
            feedback = StringUtils.EMPTY;
        }
        Update update = new Update().set("usefulness", usefulness).set("feedback", feedback).set("updateTime", LocalDateTime.now());
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ChatRecord.class);
        return updateResult.getModifiedCount() > 0;
    }

    public void batchUpdate(List<ChatRecordDTO> updates) {
        BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, ChatRecord.class);
        for (ChatRecordDTO update : updates) {
            Query query = Query.query(Criteria.where("id").is(update.getId()));
            Update updateOp = new Update().set("usefulness", update.getUsefulness()).set("feedback", update.getFeedback());
            bulkOps.updateOne(query, updateOp);
        }
        bulkOps.execute();
    }

    public boolean delete(String id, Boolean deleted) {
        Query query = new Query(Criteria.where("id").is(id));
        Update update = new Update().set("deleted", deleted);
        UpdateResult updateResult = mongoTemplate.updateFirst(query, update, ChatRecord.class);
        return updateResult.getModifiedCount() > 0;
    }

}
